<template>
  <view>
    <van-popup @close="closePop" v-model:show="isQrcode" round closeable @click-close-icon="closePop">
      <view class="pop-main">
        <image mode="scaleToFill" src="@/static/image/h5_gongzhonghao_qrcode.png" class="qr-code" />
        <view style="width: 600rpx; text-align: center; margin: 60rpx 0">长按图片关注公众号</view>
      </view>
    </van-popup>

    <van-dialog @confirm="confirm" @cancel="cancel" v-model:show="show" cancelButtonText="关注公众号领福利"
      confirmButtonText="继续支付" show-cancel-button>
      <view class="pop-mains">
        <view class="closed" @click="closePop">
          <van-icon name="cross" />
        </view>
        <view class="title">
          <view>系统提示</view>
        </view>
        <view class="contents">支付失败，真的要放弃这个机会吗？</view>
      </view>
    </van-dialog>
  </view>
</template>
<script setup>
import {
  getPayStat,
  getOpenId,
  addCircle,
  getUserInfo,
  postVip,
  overhead,
  buyShow,
} from "@/api/apiList";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";
const show = ref(false);
const isQrcode = ref(false);

const closePop = () => {
  isQrcode.value = false;
  const protocol = window.location.protocol; // 返回 "https:" 或 "http:"
  const host = window.location.host; // 返回域名和端口(如 "www.example.com" 或 "www.example.com:8080")
  const fullDomain = `${protocol}//${host}`;
  window.location.href = `${fullDomain}/h5/#/pages/index/index`;
};

onLoad(async (option) => {
  let result = "";
  let payType = uni.getStorageSync("palyType");
  const params = new URLSearchParams(window.location.search);

  let uRes = await getUserInfo();
  if (uRes.code != 200)
    return uni.showToast({
      title: "获取用户信息失败",
      icon: "none",
    });
  // 去获取微信登录code
  if (!params.get("code")) {
    const protocol = window.location.protocol; // 返回 "https:" 或 "http:"
    const host = window.location.host; // 返回域名和端口(如 "www.example.com" 或 "www.example.com:8080")

    const fullDomain = `${protocol}//${host}`;
    let redirect_uri = encodeURIComponent(
      `${fullDomain}/h5/#/pages/forSale/pages/weixinPay/`
    );
    // let redirect_uri = encodeURIComponent(
    //   "https://h5.qunxinghuzhu.com/h5/#/pages/forSale/pages/weixinPay/"
    // );
    let appId = "wx5fcd79543f91406a";
    // 跳转获取登录code
    return (window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_wechat_redirect
     `);
  }

  let errM = "";
  if (params && params.get("code")) {
    let bindRes = await getOpenId({ code: params.get("code") });
    if (bindRes.code != 200) {
      errM = bindRes.msg || "绑定openId失败";
    }
  }

  if (errM) {
    return uni.showToast({
      title: errM,
      icon: "none",
    });
  }

  if (payType == "vip") {
    result = await postVip({
      isApp: true,
    });
    // 置顶  7 == 广场置顶，8==首页置顶，2==圈子动态置顶
  } else if (payType == "7" || payType == "8" || payType == "2") {
    let obj = uni.getStorageSync("topData");
    obj.type = payType;

    // 1供需广场顶置 2首页顶置
    result = await overhead(obj);
    // 购买手机次数
  } else if (payType == "phone") {
    result = await buyShow({
      circleId: uni.getStorageSync("payId"),
      ruleId: uni.getStorageSync("palyRule"),
    });
  } else {
    // 加入圈子
    result = await addCircle({
      circleId: uni.getStorageSync("payId"),
      // circleId: 213,// 推荐人id
      userId: uni.getStorageSync("weixinUserId"),
      // userId: uni.getStorageSync("userInfo").userId,
    });
  }

  if (result.code != 200) {
    return uni.showToast({
      title: result.msg || "调取支付失败",
      icon: "none",
    });
  }

  return WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: result.data.appId, //公众号ID，由商户传入
      timeStamp: result.data.timeStamp, //new Date().getTime / 1000 + "", //时间戳，自1970年以来的秒数
      nonceStr: result.data.nonceStr, //"4325435432543254325432545432545325", //随机串
      package: result.data.packageVal, //."prepay_id=wx2309422499772669b3f4f0dc67fd370001",
      signType: result.data.signType, //"RSA", //微信签名方式：
      paySign: result.data.paySign, //微信签名
    },
    function (res) {
      if (res.err_msg == "get_brand_wcpay_request:ok") {
        // 清除缓存
        // uni.removeStorageSync("payId");
        // uni.removeStorageSync("palyType");
        // uni.removeStorageSync("palyRule");
        // uni.removeStorageSync("topData");
        // uni.removeStorageSync("weixinUserId");
        // uni.removeStorageSync("resFrom");

        uni.showToast({
          title: "支付成功",
          icon: "success",
        });
        // setTimeout(() => {
        //   const protocol = window.location.protocol; // 返回 "https:" 或 "http:"
        //   const host = window.location.host; // 返回域名和端口(如 "www.example.com" 或 "www.example.com:8080")
        //   const fullDomain = `${protocol}//${host}`;
        //   window.location.href = `${fullDomain}/h5/#/pages/index/pages/groupDetail?id=` + uni.getStorageSync("payId");
        // }, 1000)

        setTimeout(() => {
          uni.redirectTo({
            url:
              "/pages/index/pages/groupDetail?id=" + uni.getStorageSync("payId"),
          });
        }, 1000)
      } else {
        show.value = true;
        // return uni.showModal({
        //   title: "系统提示",
        //   content: "支付失败，真的要放弃这个机会吗？",
        //   icon: "error",
        //   confirmText: "继续支付",
        //   cancelText: "关注公众号领福利",
        //   success: (re) => {
        //     if (re.confirm) {
        //       const protocol = window.location.protocol; // 返回 "https:" 或 "http:"
        //       const host = window.location.host; // 返回域名和端口(如 "www.example.com" 或 "www.example.com:8080")

        //       const fullDomain = `${protocol}//${host}`;

        //       window.location.href =
        //         `${fullDomain}/h5/#/pages/forSale/pages/weixinPay?time=` +
        //         new Date().getTime();
        //       // window.location.href =
        //       //   "https://h5.qunxinghuzhu.com/h5/#/pages/forSale/pages/weixinPay?time=" +
        //       //   new Date().getTime();
        //     } else {
        //       return (isQrcode.value = true);
        //     }
        //   },
        // });
      }
    }
  );
});

const cancel = () => {
  isQrcode.value = true
}
const confirm = () => {
  const protocol = window.location.protocol; // 返回 "https:" 或 "http:"
  const host = window.location.host; // 返回域名和端口(如 "www.example.com" 或 "www.example.com:8080")

  const fullDomain = `${protocol}//${host}`;

  window.location.href =
    `${fullDomain}/h5/#/pages/forSale/pages/weixinPay?time=` +
    new Date().getTime();
  // window.location.href =
  //   "https://h5.qunxinghuzhu.com/h5/#/pages/forSale/pages/weixinPay?time=" +
  //   new Date().getTime();
}
</script>
<style>
.qr-code {
  width: 600rpx;
  height: 600rpx;
}

.pop-mains {
  .closed {
    display: flex;
    justify-content: flex-end;
    padding: 15rpx;
  }

  .title {
    display: flex;
    justify-content: center;
  }

  .contents {
    padding: 20rpx;
    font-size: 24rpx;
    text-align: center;
    color: #323233;
  }
}
</style>
